package cn.steel.controller.buyer;

import cn.hutool.core.bean.BeanUtil;
import cn.steel.base.ResponseData;
import cn.steel.domain.dto.OrderDto;
import cn.steel.domain.dto.OrderItemDto;
import cn.steel.domain.entity.Order;
import cn.steel.domain.entity.Product;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.domain.entity.User;
import cn.steel.domain.vo.CartVo;
import cn.steel.domain.vo.ProductVo;
import cn.steel.service.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/buyer")
@Api(tags = "买家商品页面管理")
@RequiredArgsConstructor
public class BuyerProductController {

    private final ProductService productService;
    private final FavoriteService favoriteService;
    private final CartService cartService;
    private final SupplierInfoService supplierInfoService;
    private final BrowseHistoryService browseHistoryService;
    private final OrderService orderService;

    @ApiOperation("显示商品列表页面")
    @GetMapping
    public String productList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) Long categoryId,
            Model model) {
        log.info("显示商品列表页面: page={}, size={}, search={}, categoryId={}",
                page, size, search, categoryId);
        PageHelper.startPage(page, size);
        Page<ProductVo> pageResult = productService.getProductsPaginated(search, null, categoryId, null, null, 1);
        model.addAttribute("products", pageResult.getResult());
        model.addAttribute("totalPages", pageResult.getPages());
        model.addAttribute("totalItems", pageResult.getTotal());
        model.addAttribute("currentPage", pageResult.getPageNum());
        model.addAttribute("pageSize", size);
        model.addAttribute("search", search);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("categories", productService.getCategories());
        return "buyer/product_list";
    }

    @ApiOperation("显示商品详情页面")
    @GetMapping("/product/{id}")
    public String productDetails(@PathVariable Long id, @SessionAttribute(value = "user", required = false) User user, Model model) {
        log.info("显示商品详情页面: productId={}", id);
        Product product = productService.getProductById(id);
        if (product == null) {
            return "redirect:/buyer";
        }
        ProductVo productVo = BeanUtil.toBean(product, ProductVo.class);
        productVo.setCategoryName(product.getCategoryId() != null ? productService.findCategoryById(product.getCategoryId()) : null);
        model.addAttribute("product", productVo);
        // 获取供应商信息
        try {
            SupplierInfo supplierInfo = supplierInfoService.getSupplierInfoByUserId(product.getSupplierId());
            model.addAttribute("supplierInfo", supplierInfo);
        } catch (IllegalArgumentException e) {
            log.warn("无法获取供应商信息: supplierId={}", product.getSupplierId());
            model.addAttribute("supplierInfo", null); // 供应商不存在时传递 null
        }
        // 仅当用户是买家时记录浏览历史
        if (user != null && "BUYER".equals(user.getRole())) {
            browseHistoryService.addBrowseHistory(user.getId(), id);
        }
        return "buyer/product_details";
    }
    @ApiOperation("添加商品到购物车")
    @PostMapping("/cart/add")
    public String addToCart(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Long productId,
            @RequestParam Integer quantity,
            RedirectAttributes redirectAttributes,
            @RequestHeader(value = "Referer", defaultValue = "/buyer") String referer) {
        log.info("添加商品到购物车: userId={}, productId={}, quantity={}", user != null ? user.getId() : null, productId, quantity);
        if (user == null || !"BUYER".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("error", "请以买家身份登录后操作");
            return "redirect:/login?url=" + referer;
        }
        try {
            cartService.addToCart(user.getId(), productId, quantity);
            redirectAttributes.addFlashAttribute("success", true);
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
        }
        return "redirect:" + referer;
    }

    @ApiOperation("立即购买")
    @PostMapping("/checkout")
    public String checkout(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Long productId,
            @RequestParam Integer quantity,
            HttpSession session,
            RedirectAttributes redirectAttributes) {
        if (user == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "请登录后操作");
            return "redirect:/login?url=/buyer/product/" + productId;
        }
        if (!"BUYER".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "仅买家用户可以操作");
            return "redirect:/login?url=/buyer/product/" + productId;
        }
        log.info("立即购买: userId={}, productId={}, quantity={}", user.getId(), productId, quantity);

        try {
            // 1. 获取商品信息
            Product product = productService.getProductById(productId);
            if (product == null) {
                redirectAttributes.addFlashAttribute("errorMessage", "商品不存在");
                return "redirect:/buyer/product/" + productId;
            }

            // 2. 检查库存
            if (product.getInventory() < quantity) {
                redirectAttributes.addFlashAttribute("errorMessage", "库存不足");
                return "redirect:/buyer/product/" + productId;
            }

            // 3. 创建订单
            OrderDto orderDto = new OrderDto();
            orderDto.setBuyerId(user.getId());
            orderDto.setStatus("PENDING");
            orderDto.setTotalAmount(product.getPrice().multiply(new BigDecimal(quantity)).doubleValue());

            // 4. 创建订单项
            OrderItemDto itemDto = new OrderItemDto();
            itemDto.setProductId(productId);
            itemDto.setProductName(product.getName());
            itemDto.setSpecification(product.getSpecification());
            itemDto.setQuantity(quantity);
            itemDto.setPrice(product.getPrice().doubleValue());
            itemDto.setTotalPrice(product.getPrice().multiply(new BigDecimal(quantity)).doubleValue());
            itemDto.setSupplierId(product.getSupplierId());
            itemDto.setSupplierName(product.getSupplierName());

            orderDto.setItems(List.of(itemDto));

            // 5. 保存订单
            Order order = orderService.createOrder(orderDto);

            // 6. 将订单ID存入session
            session.setAttribute("pendingOrderId", order.getId());

            return "redirect:/buyer/receipt";
        } catch (Exception e) {
            log.error("创建订单失败", e);
            redirectAttributes.addFlashAttribute("errorMessage", "创建订单失败: " + e.getMessage());
            return "redirect:/buyer/product/" + productId;
        }
    }
    @ApiOperation("收藏商品")
    @PostMapping("/favorite")
    public String addToFavorites(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam Long productId,
            RedirectAttributes redirectAttributes) {
        if (user == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "请登录后操作");
            return "redirect:/login?url=/buyer/product/" + productId;
        }
        if (!"BUYER".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "仅买家用户可以操作");
            return "redirect:/login?url=/buyer/product/" + productId;
        }
        log.info("收藏商品: userId={}, productId={}", user.getId(), productId);
        favoriteService.addToFavorites(user.getId(), productId);
        return "redirect:/buyer/product/" + productId;
    }

    @ApiOperation("去结算购买")
    @PostMapping("/checkout/multi")
    public String multiCheckout(
            @SessionAttribute(value = "user", required = false) User user,
            @RequestParam("productIds") List<Long> productIds,
            @RequestParam("quantities") List<Integer> quantities,
            HttpSession session,
            RedirectAttributes redirectAttributes) {

        // 1. 用户验证
        if (user == null) {
            redirectAttributes.addFlashAttribute("errorMessage", "请登录后操作");
            return "redirect:/login?url=/buyer/cart/view";
        }
        if (!"BUYER".equals(user.getRole())) {
            redirectAttributes.addFlashAttribute("errorMessage", "仅买家用户可以操作");
            return "redirect:/login?url=/buyer/cart/view";
        }

        // 2. 参数校验
        if (productIds == null || quantities == null || productIds.size() != quantities.size()) {
            redirectAttributes.addFlashAttribute("errorMessage", "参数不合法");
            return "redirect:/buyer/cart/view";
        }

        // 3. 准备订单数据
        List<Product> products = new ArrayList<>();
        List<OrderItemDto> items = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        try {
            // 4. 检查每个商品的库存并计算总金额
            for (int i = 0; i < productIds.size(); i++) {
                Long productId = productIds.get(i);
                Integer quantity = quantities.get(i);

                // 获取商品信息
                Product product = productService.getProductById(productId);
                if (product == null) {
                    redirectAttributes.addFlashAttribute("errorMessage", "商品ID " + productId + " 不存在");
                    return "redirect:/buyer/cart/view";
                }

                // 检查库存
                if (product.getInventory() < quantity) {
                    redirectAttributes.addFlashAttribute("errorMessage",
                            "商品 [" + product.getName() + "] 库存不足，当前库存: " + product.getInventory());
                    return "redirect:/buyer/cart/view";
                }

                // 计算小计
                BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(quantity));

                // 创建订单项
                OrderItemDto itemDto = new OrderItemDto();
                itemDto.setProductId(productId);
                itemDto.setProductName(product.getName());
                itemDto.setSpecification(product.getSpecification());
                itemDto.setQuantity(quantity);
                itemDto.setPrice(product.getPrice().doubleValue());
                itemDto.setTotalPrice(itemTotal.doubleValue());
                itemDto.setSupplierId(product.getSupplierId());
                itemDto.setSupplierName(product.getSupplierName());

                items.add(itemDto);
                products.add(product);
                totalAmount = totalAmount.add(itemTotal);
            }

            // 5. 创建订单DTO
            OrderDto orderDto = new OrderDto();
            orderDto.setBuyerId(user.getId());
            orderDto.setStatus("PENDING");
            orderDto.setTotalAmount(totalAmount.doubleValue());
            orderDto.setItems(items);

            // 6. 保存订单
            Order order = orderService.createOrder(orderDto);

            // 8. 将订单ID存入session
            session.setAttribute("pendingOrderId", order.getId());

            return "redirect:/buyer/receipt";

        } catch (Exception e) {
            log.error("创建订单失败", e);
            redirectAttributes.addFlashAttribute("errorMessage", "创建订单失败: " + e.getMessage());
            return "redirect:/buyer/cart/view";
        }
    }
}